/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: KlineActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.ui;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bhex.kline.widget.TabButtonItem;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.R;
import io.bhex.app.event.PriceDigitsEvent;
import io.bhex.app.kline.BaseKlineShareActivity;
import io.bhex.app.kline.adapter.KlineFragmentAdapter;
import io.bhex.app.kline.bean.PriceDigits;
import io.bhex.app.kline.presenter.KlinePresenter;
import io.bhex.app.market.api.MarketApi;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.ShareConfigUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.PopWindowList;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.images.CImageLoader;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.SMFrameCallback;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.bhex.sdk.data_manager.AssetUtilsManager;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.enums.COIN_TYPE;
import io.bhex.sdk.invite.bean.InviteResponse;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.OptionSymbolStatusBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.trade.OptionApi;

public class KlineExtActivity extends BaseKlineShareActivity<KlinePresenter, KlinePresenter.KlineUI>
        implements KlinePresenter.KlineUI, View.OnClickListener, AssetUtilsManager.IndexChangeInterface {

    private List<Pair<String, Fragment>> items;
    private List<Pair<String, Fragment>> itemsKline;
    private String coinPair = "";//币对


    private int currentOrderTabPosition;//当前选择的订单tab
    RelativeLayout.LayoutParams layoutParamsViewPagerKline;
    //private RelativeLayout tabLinear;
    private LinearLayout tabLinear1;
    private BookListFragment bookListFragment;
    List<PriceDigits.DigitsItem> digitsList = new ArrayList<>();
    //是否显示着K线Tab图
    private RelativeLayout klineLinear;
    //    private boolean isShowKlineTab = false;
    //private RelativeLayout klineTabRela;
    private LayoutInflater layoutInflater;
    private TickerBean currentTicker;
    private String exchangeId = "";
    //合并深度小数
    private String mergeDigitsStr = "";
    private boolean isFavorite;//是否是自选
    private int currentTabId = R.id.tab_kline_name;
    private final int CHART_TYPE_NOT_KLINE = -1;//不是K线chart
    //private int KLINE_TYPE_TIME=0x10;//分时
    //private int KLINE_TYPE_CANDLE=0x11;//蜡烛图
    //private int lastKlineType = KLINE_TYPE_CANDLE;//默认是蜡烛图 15分钟线
    private boolean currentShowKlineTab = false;//子K线选择Tab当前显示状态
    private int currentKlineType = KlineFragment.KLINE_TYPE_MINUTE_FIFTEEN;//默认15分钟线
    private String baseToken = "";
    private String quoteToken = "";
    private CoinPairBean coinPairBean;
    private View verticalScreen;
    private PopWindowList popListView;

    //分钟线popup tab数组
    private String[] tabMinuteArray;
    private PopWindowList popTabListView;
    private TextView tabLandMinutes;
    private ImageView tabLandMinutesIcon;
    //是否是深度tab
    private boolean isDepthTab = false;

    public String baseTokenName = "";
    public String quoteTokenName = "";
    private RelativeLayout.LayoutParams indexLandViewLayoutParams;
    private int baseDigit;
    private int quoteDigit;
    private boolean isDefaultSeeDepth;
    private boolean bShowIndex = false;

    private Timer timer;
    private TimerTask taskSettle;
    private TimerTask task;
    private static final int nPeriod = 1 * 1000;

    private Handler mHandler;
    private OptionSymbolStatusBean.OptionSymbolStatus mOptionSymbolStatus;
    private static final int TIMER_MESSAGE = 0X1;

    private static final int TIMER_SETTLE_MESSAGE = 0X2;

    @Override
    protected KlinePresenter createPresenter() {
        return new KlinePresenter(this);
    }

    @Override
    protected KlinePresenter.KlineUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);


        //this.setTopbarNight(topBar);
        //topBar收藏按钮
        ImageView favoriteImg = topBar.getRightImg();
        //topBar分享按钮
        ImageView rightImg2 = topBar.getRightImg2();
        rightImg2.setVisibility(View.VISIBLE);
        rightImg2.setImageResource(R.mipmap.ic_share);
        rightImg2.setOnClickListener(v -> {
            shotScreenShare();
        });


        Intent intent = getIntent();
        if (intent != null) {
            isDefaultSeeDepth = intent.getBooleanExtra(AppData.INTENT.DEPTHVIEW, false);
            coinPairBean = (CoinPairBean) intent.getSerializableExtra(AppData.INTENT.SYMBOLS);
//            String symbolId = intent.getStringExtra(AppData.INTENT.SYMBOLS);
//            coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(symbolId);
            if (coinPairBean != null) {
                coinPair = coinPairBean.getSymbolId();
                exchangeId = coinPairBean.getExchangeId();
                mergeDigitsStr = coinPairBean.getDigitMerge();
                isFavorite = SymbolDataManager.GetInstance().isFavorite(coinPairBean);
                baseToken = coinPairBean.getBaseTokenId();
                quoteToken = coinPairBean.getQuoteTokenId();
                baseDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + baseToken);
                quoteDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken);
                baseTokenName = coinPairBean.getBaseTokenName();
                quoteTokenName = coinPairBean.getQuoteTokenName();

                //委托 最新成交 title设置
                /*viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), baseTokenName));
                viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), baseTokenName));
                viewFinder.textView(R.id.title_price).setText(String.format(getString(R.string.string_price_ph), quoteTokenName));
                viewFinder.textView(R.id.title_deal_price).setText(String.format(getString(R.string.string_price_ph), quoteTokenName));
                viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), baseTokenName));*/

                if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
                    //币币
                    if (!TextUtils.isEmpty(coinPair)) {
                        topBar.setTitle(coinPairBean.getBaseTokenName() + "/" + coinPairBean.getQuoteTokenName());
                    }
                    ((TextView) findViewById(R.id.coinPairName)).setText(baseTokenName + "/" + quoteTokenName); //横屏sybolName

                    //币币收藏按钮
                    favoriteImg.setVisibility(View.VISIBLE);
                    topBar.setRightImg(isFavorite ? R.mipmap.ic_favorite_white_check : R.mipmap.ic_favorite_white);
                    topBar.setRightOnClickListener(v -> {
                        if (TextUtils.isEmpty(coinPair) ||TextUtils.isEmpty(exchangeId)) {
                            return;
                        }

                        MarketApi.favoriteCoin(KlineExtActivity.this, coinPairBean, new MarketApi.CallBack() {
                            @Override
                            public void success(Object obj) {
                                isFavorite = !isFavorite;
                                coinPairBean.setFavorite(isFavorite);
                                SymbolDataManager.GetInstance().cancelLocalFavorite(coinPairBean);
                                CoinPairBean coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(coinPair);
                                if(coinPairBean!=null){
                                    coinPairBean.setFavorite(isFavorite);
                                }
                                topBar.setRightImg(isFavorite ? R.mipmap.icon_favorite_checked : R.mipmap.icon_favorite);
                                KlineUtils.saveFavorite(coinPairBean);
                            }

                            @Override
                            public void failed() {

                            }
                        });
                    });

                    //顶部最新价等指标
                    viewFinder.find(R.id.top_market_data).setVisibility(View.VISIBLE); //币币
                    viewFinder.find(R.id.top_option_data).setVisibility(View.GONE);  //期权

                } else if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
                    //期权

                    favoriteImg.setVisibility(View.GONE);
                    topBar.setTitle(coinPairBean.getSymbolName());
                    ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName()); //横屏sybolName
                    viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase));
                    viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout));
                    if (coinPairBean.baseTokenOption != null && !TextUtils.isEmpty(coinPairBean.getSymbolName()) && !TextUtils.isEmpty(coinPairBean.baseTokenOption.isCall)) {
                        String call = "";
                        boolean optionCall = KlineUtils.isOptionCall(coinPairBean.baseTokenOption.isCall);
                        if (optionCall) {
                            call = getString(R.string.string_option_call);
                            topBar.setLeftTextAndBackGround(call, R.style.Mini_Green, R.drawable.bg_corner_rect_green_night);
                        } else {
                            call = getString(R.string.string_option_put);
                            topBar.setLeftTextAndBackGround(call, R.style.Mini_Red, R.drawable.bg_corner_rect_red_night);
                        }
                        topBar.setTitle(coinPairBean.getSymbolName());
                        topBar.setTitleAppearance(R.style.BodyL_Dark_Bold_night);
                        //topBar.setTitleLength(180);
                        //买卖按钮
                        viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase) + "(" + getString(optionCall ? R.string.string_option_purchase : R.string.string_option_sellout) + ")");
                        viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout) + "(" + getString(optionCall ? R.string.string_option_sellout : R.string.string_option_purchase) + ")");

                    }

//                    viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), getString(R.string.string_option_unit)));
//                    viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), getString(R.string.string_option_unit)));
//                    viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), getString(R.string.string_option_unit)));

                    //顶部最新价等指标
                    viewFinder.find(R.id.top_market_data).setVisibility(View.GONE); //币币
                    viewFinder.find(R.id.top_option_data).setVisibility(View.VISIBLE);  //期权

                } else if (KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())) {
                    //合约
                    favoriteImg.setVisibility(View.GONE);
                    topBar.setTitle(coinPairBean.getSymbolName());
                    ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName()); //横屏sybolName

                    /*viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), getString(R.string.string_option_unit)));
                    viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), getString(R.string.string_option_unit)));
                    viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), getString(R.string.string_option_unit)));*/

                    //顶部最新价等指标
                    viewFinder.find(R.id.top_market_data).setVisibility(View.VISIBLE); //币币
                    viewFinder.find(R.id.top_option_data).setVisibility(View.GONE);  //期权
                    //买卖按钮
                    viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_futures_open_long) + ")");
                    viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_futures_open_short) + ")");
                }

            } else {
//                ToastUtils.showShort(getString(R.string.string_net_exception));
            }

        }


        tabMinuteArray = new String[]{getResources().getString(R.string.kline_thirty_minutes), getResources().getString(R.string.kline_fifteen_minutes), getResources().getString(R.string.kline_five_minutes), getResources().getString(R.string.kline_one_minute)};

        klineLinear = viewFinder.find(R.id.kline_linear);
        layoutInflater = LayoutInflater.from(this);
        //
        //横屏ticker
        //topMarketViewLand =  viewFinder.find(R.id.layout_land_top);
        //topMarketViewLand = layoutInflater.inflate(R.layout.include_latest_market_header_land_layout, klineLinear, false);
        //竖屏ticker
        topMarketView = viewFinder.find(R.id.top_market_data);
        topOptionView = viewFinder.find(R.id.top_option_data);
        //marketDividerView = viewFinder.find(R.id.market_divider);
        //横屏指标切换按钮


        layoutParamsViewPagerKline = (RelativeLayout.LayoutParams) viewPagerKline.getLayoutParams();
        viewPager = viewFinder.find(R.id.viewPager);
        viewPager.setScanScroll(false);//设置不可以滑动切换页
        tab = viewFinder.find(R.id.tab);
        tab.setTabTextColors(SkinColorUtil.getKlinDark(this), getResources().getColor(R.color.blue));
        buysellLinear = viewFinder.find(R.id.buysell_linear);
        //entrustHeader = viewFinder.find(R.id.entrust_header);
        //latestHeader = viewFinder.find(R.id.latest_header);
        tabLinear1 = viewFinder.find(R.id.tabLinear1);

        initKlineFragmentTab();
        initOrderFragmentTab();
        klineTabMap.put(R.id.tab_minute_fifteen, viewFinder.textView(R.id.tab_minute_fifteen));

        swtichIndexTab(R.id.tab_ma, R.id.tab_land_ma);
        swtichSubIndexTab(R.id.tab_vol, R.id.tab_land_vol);

//        ((TextView) (tabLandView.findViewById(R.id.tab_land_15m))).setTextColor(getResources().getColor(R.color.blue));
//        ((TextView) (viewFinder.find(R.id.tab_minute_fifteen))).setTextColor(getResources().getColor(R.color.blue));

        if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
            //期权
            viewFinder.textView(R.id.option_exercise_point_title).setText(getString(R.string.string_exercise_point) + "(" + quoteTokenName + ")");
            viewFinder.textView(R.id.option_exercise_price_title).setText(getString(R.string.string_exercise_price) + "(" + quoteTokenName + ")");
            viewFinder.textView(R.id.option_maxPayOff_title).setText(getString(R.string.string_option_maxPayOff)/* + "(" + quoteTokenName + "/"+ getString(R.string.string_option_unit)+")"*/);
            viewFinder.textView(R.id.option_exercise_price).setText(coinPairBean.baseTokenOption.strikePrice);
            viewFinder.textView(R.id.option_maxPayOff).setText(coinPairBean.baseTokenOption.maxPayOff);
        } else if (KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())) {
            //合约
        } else {
            viewFinder.find(R.id.top_market_data).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.top_option_data).setVisibility(View.GONE);
        }

        if (coinPairBean != null) {
            if (coinPairBean.getCoinType() == COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType()) {//合约
                viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_futures_open_long) + ")");
                viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_futures_open_short) + ")");
            }
        }

        //分享view初始化
        shareView = layoutInflater.inflate(R.layout.flater_share_qrcode_layout, null, false);
        shareLogoImg = shareView.findViewById(R.id.logo);
        shareName = shareView.findViewById(R.id.name);
        shareDesp = shareView.findViewById(R.id.desp);
        shareQrcodeImg = shareView.findViewById(R.id.qrcode);
        sharePreView = viewFinder.find(R.id.preView);
        sharePreViewImg = viewFinder.imageView(R.id.preViewImg);
        ShareConfigBean shareConfig = ShareConfigUtils.getShareConfig();
        setShareConfig(shareConfig);


        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                // 指数 时间
                mHandler.sendEmptyMessage(TIMER_MESSAGE);
            }
        };
        if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
            //期权   交割状态定时刷新
            timer.schedule(task, 50, nPeriod);
            taskSettle = new TimerTask() {
                @Override
                public void run() {
                    long time = Long.valueOf(coinPairBean.baseTokenOption.settlementDate) - System.currentTimeMillis();
                    if (mOptionSymbolStatus != null && mOptionSymbolStatus.settleStatus != null && mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DONE")) {

                    } else if (time <= 0) {
                        mHandler.sendEmptyMessage(TIMER_SETTLE_MESSAGE);
                    }
                }
            };

            timer.schedule(taskSettle, 50, nPeriod * 6);
        }

        //SMFrameCallback.getInstance().start();
    }

    private void stopSettleTimer() {
        if (taskSettle != null) {
            taskSettle.cancel();
        }
    }

    @Override
    public void setShareConfig(ShareConfigBean response) {
        if (response != null) {
            shareConfig = response;
            if (shareConfig != null) {
                shareName.setText(response.getTitle());
                shareDesp.setText(response.getDescription());
                String logoUrl = response.getLogoUrl();
                String openUrl = response.getOpenUrl();
                TextUtils.isEmpty(openUrl);
                CImageLoader.getInstance().load(shareLogoImg, logoUrl);
            }
        }
    }

    @Override
    public void showShareInfo(InviteResponse response) {
        if (response != null) {
            shareUrl = response.getShareUrl();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case TIMER_MESSAGE:
                        try {

                            if (coinPairBean != null && coinPairBean.baseTokenOption != null) {
                                if (mOptionSymbolStatus != null && mOptionSymbolStatus.settleStatus != null && (mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DOING") || mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DONE"))) {

                                    viewFinder.textView(R.id.option_exercise_point_title).setText(getString(R.string.string_option_delivery_price));
                                    if (mOptionSymbolStatus.settleDetail != null && !TextUtils.isEmpty(mOptionSymbolStatus.settleDetail.settlementPrice)) {
                                        String price = NumberUtils.roundFormatDown(mOptionSymbolStatus.settleDetail.settlementPrice, SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken));
                                        viewFinder.textView(R.id.option_exercise_point).setText(price);
                                    } else
                                        viewFinder.textView(R.id.option_exercise_point).setText("--");
                                } else {
                                    viewFinder.textView(R.id.option_exercise_point_title).setText(getString(R.string.string_exercise_point));
                                    String indexData = NumberUtils.roundFormatDown(AssetUtilsManager.GetInstance().getSymbolIndexOfOption(coinPairBean.baseTokenOption.indexToken), SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken));
                                    viewFinder.textView(R.id.option_exercise_point).setText(indexData);
                                }
                            } else
                                viewFinder.textView(R.id.option_exercise_point).setText("--");

                            if (coinPairBean.baseTokenOption != null) {
                                long time = Long.valueOf(coinPairBean.baseTokenOption.settlementDate) - System.currentTimeMillis();
                                if (time <= 0) {
                                    if (mOptionSymbolStatus != null && mOptionSymbolStatus.settleStatus != null && mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DONE"))
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_over_delivery));
                                    else
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_over_deliverying));
                                } else {
                                    int day = Math.round(time / 1000 / 60 / 60 / 24);
                                    // 时
                                    int hour = Math.round(time / 1000 / 60 / 60 % 24);
                                    // 分
                                    int minute = Math.round(time / 1000 / 60 % 60);
                                    // 秒
                                    int second = Math.round(time / 1000 % 60);

                                    if (day > 0)
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_delivery_timer) + day + getString(R.string.string_option_d));
                                    else
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_delivery_timer) + String.format(getString(R.string.string_option_h_m_s), hour, minute, second));
                                }
                            }
                        } catch (Exception e) {

                        }

                        break;
                    case TIMER_SETTLE_MESSAGE:
                        getSettleStatus();
                        break;
                }
            }
        };

        init(getContentResolver(), this);
        register();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (coinPairBean != null && coinPairBean.baseTokenOption != null) {
            AssetUtilsManager.GetInstance().AddIndexObserver(this);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //tab_kline.addTabItemIcon(4);

    }

    @Override
    protected void onPause() {
        super.onPause();
        AssetUtilsManager.GetInstance().removeIndexObserver(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();
        }
        if (taskSettle != null) {
            taskSettle.cancel();
        }

        if (timer != null) {
            timer.purge();
            timer.cancel();
        }
        unregister();
    }

    @Override
    protected void addEvent() {
        super.addEvent();

        tab_kline = findViewById(R.id.tab_kline);
        ArrayList<TabButtonItem> tabList  = getPresenter().getKLineTab();
        tab_kline.setTabList(tabList);
        tab_kline.setCheckTabListener(this);

        //tab_kline.addTabItemIcon(4);

        viewFinder.find(R.id.iv_full).setOnClickListener(this);
        topMarketViewLand.findViewById(R.id.tab_verticalscreen).setOnClickListener(this);
        //viewFinder.find(R.id.tab_verticalscreen).setOnClickListener(this);
        viewFinder.find(R.id.btn_buy).setOnClickListener(this);
        viewFinder.find(R.id.btn_sell).setOnClickListener(this);


        viewFinder.find(R.id.preView).setOnClickListener(this);
        viewFinder.find(R.id.preViewImg).setOnClickListener(this);

    }
    @Override
    public void onClick(View v) {
        if (popTabListView != null) {
            popTabListView.closePop();
        }
        switch (v.getId()) {
            case R.id.preView:
            case R.id.preViewImg:
                sharePreView.setVisibility(View.GONE);
                break;


            case R.id.iv_full:
                //flag = tab_kline.selectIsLastIndex();
                //viewFinder.find(R.id.iv_full).setVisibility(View.GONE);
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            case R.id.tab_verticalscreen:
                //viewFinder.find(R.id.iv_full).setVisibility(View.VISIBLE);
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
                break;
            case R.id.title_decimal_num://委托订单-盘口小数
                if (!TextUtils.isEmpty(mergeDigitsStr)) {
                    String[] digitsArray = mergeDigitsStr.split(",");
                    if (digitsArray.length > 0) {
                        digitsList.clear();
                        for (String s : digitsArray) {
                            PriceDigits.DigitsItem digitsItem = new PriceDigits.DigitsItem();
                            String name = NumberUtils.calNumerName(this, s);
                            digitsItem.setDigitsName(name);
                            digitsItem.setDigits(s);
                            digitsList.add(digitsItem);
                        }
                        String[] itemNames = new String[digitsList.size()];
                        for (int i = 0; i < digitsList.size(); i++) {
                            itemNames[i] = digitsList.get(i).getDigitsName();
                        }
//                        new AlertView(getString(R.string.string_depth_digits), null, getString(R.string.string_cancel), null, itemNames, this, AlertView.Style.ActionSheet, this).show();
                        if (popListView == null) {
                            popListView = new PopWindowList(this, new PopWindowList.ListOnItemClick() {
                                @Override
                                public void onItemClick(String item, int layoutPosition) {
                                    String digits = digitsList.get(layoutPosition).getDigits();
//                                    ToastUtils.showShort(layoutPosition+" "+digits);
                                    //深度小数通知
                                    EventBus.getDefault().post(new PriceDigitsEvent(digits));
                                    viewFinder.textView(R.id.title_decimal_num).setText(item);
                                }
                            });
                        }
                        popListView.setAdapter(Arrays.asList(itemNames));
                        popListView.setBackgroudRes(CommonUtil.isBlackMode() ? R.mipmap.icon_popup_bg_up_night : R.mipmap.icon_popup_bg_up, true);
                        popListView.showPopList(viewFinder.find(R.id.title_decimal_num), 0, 0);
                    }

                }

                break;

            case R.id.btn_buy:
                if (coinPairBean != null) {
                    coinPairBean.setBuyMode(true);
                    coinPairBean.setNeedSwitchTradeTab(true);
                    //IntentUtils.goTrade(this,coinPairBean);
//                ToastUtils.showShort("Kline Post buy");
                    finish();
                    EventBus.getDefault().postSticky(coinPairBean);
                }
                break;
            case R.id.btn_sell:
                if (coinPairBean != null) {
                    coinPairBean.setBuyMode(false);
                    coinPairBean.setNeedSwitchTradeTab(true);
//                    IntentUtils.goTrade(this,coinPairBean);
//                ToastUtils.showShort("Kline Post sell");
                    finish();
                    EventBus.getDefault().postSticky(coinPairBean);
                }
                break;

        }
    }

    private int lastIndexTab = -1;
    private int lastIndexLandTab = -1;

    private void swtichIndexTab(int indexTab, int indexLandTab) {
        if (lastIndexTab != -1) {
            viewFinder.textView(lastIndexTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
        if (lastIndexLandTab != -1) {
            viewFinder.textView(lastIndexLandTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }

    }

    private int lastSubIndexTab = -1;
    private int lastSubIndexLandTab = -1;

    private void swtichSubIndexTab(int indexTab, int indexLandTab) {
        if (lastSubIndexTab != -1) {
            viewFinder.textView(lastSubIndexTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
        if (lastSubIndexLandTab != -1) {
            viewFinder.textView(lastSubIndexLandTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
    }

    /**
     * 切换K线图以及各种状态切换
     *
     * @param tabId
     * @param klineType
     */

    private void switchKline(int tabId, int klineType) {
        if (tabId == R.id.tab_depth) {
            if (isVerticalScreen) {
                isDepthTab = true;
            }
            /***深度**/
            if (currentTabId != R.id.tab_depth) {
                switchKlineTabIndicator(false);
                switchShowKlineTabView(false);
                viewPagerKline.setCurrentItem(0);
            } else {
                //二次点击不处理
            }
        } else {
            if (isVerticalScreen) {
                isDepthTab = false;
            }
            /**K线的tab情况下*******/
            if (tabId == R.id.tab_kline) {
                /****判断切换Tab情况下*********/
                if (currentTabId == R.id.tab_depth) {
                    //当前在深度图tab下
                    switchKlineTabIndicator(true);
                    switchShowKlineTabView(false);
                    /****默认是15分钟线***/
                    switchDefaultKline(currentKlineType);


                } else {
                    //当前在K线tab下 所以直接显示选择子K线tab
                    switchKlineTabIndicator(true);
                    switchShowKlineTabView(!currentShowKlineTab);
                }
            } else {
                swtichKlineTab(tabId);
                viewPagerKline.setCurrentItem(1);
                klineFragment.setKlineType(klineType);
                currentKlineType = klineType;

                switchShowKlineTabView(false);
            }

        }
        currentTabId = tabId;

    }

    /****默认是15分钟线
     * @param currentKlineType***/
    private void switchDefaultKline(int currentKlineType) {
        viewPagerKline.setCurrentItem(1);
        klineFragment.setKlineType(currentKlineType);
    }

    HashMap<Integer, TextView> klineTabMap = new HashMap<Integer, TextView>();
    HashMap<Integer, TextView> landTabMap = new HashMap<Integer, TextView>();

    private void swtichKlineTab(int tabId) {

//        tabTv.setTextColor(getResources().getColor(R.color.color_white));
        klineTabMap.put(tabId, viewFinder.textView(tabId));
        if (!klineTabMap.isEmpty()) {
            for (int id : klineTabMap.keySet()) {
                if (id == tabId) {
                    TextView tabTv = viewFinder.textView(tabId);
                    tabTv.setTextColor(getResources().getColor(R.color.blue));
                    if (viewFinder.textView(R.id.tab_kline_name) != null)
                        viewFinder.textView(R.id.tab_kline_name).setText(tabTv.getText().toString());
                } else {
                    viewFinder.textView(id).setTextColor(CommonUtil.isBlackMode() ? getResources().getColor(R.color.dark_night) : getResources().getColor(R.color.dark));
                }
            }
        }

    }

    /**
     * 切换显示K线tab选项视图
     */
    private void switchShowKlineTabView(boolean isShowKlineTab) {
        if (isShowKlineTab) {
            DebugLog.e("TAB", "TAB显示");
            viewFinder.find(R.id.tabLinear1).setVisibility(View.VISIBLE);
        } else {
            DebugLog.e("TAB", "TAB隐藏");
            viewFinder.find(R.id.tabLinear1).setVisibility(View.GONE);
        }
        currentShowKlineTab = isShowKlineTab;

    }

    /**
     * 切换tab底部颜色
     *
     * @param isKlineIndicator
     */
    private void switchKlineTabIndicator(boolean isKlineIndicator) {
        if (isKlineIndicator) {
            viewFinder.textView(R.id.tab_kline_name).setTextColor(getResources().getColor(R.color.blue));
            viewFinder.imageView(R.id.tab_kline_selctec_icon).setImageResource(R.mipmap.icon_arrow_down_blue);
            viewFinder.textView(R.id.tab_kline_depth).setTextColor(SkinColorUtil.getDark(this));
            viewFinder.find(R.id.tab_indicator_kline).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.tab_indicator_depth).setVisibility(View.INVISIBLE);
        } else {
            viewFinder.textView(R.id.tab_kline_name).setTextColor(SkinColorUtil.getDark(this));
            viewFinder.imageView(R.id.tab_kline_selctec_icon).setImageResource(R.mipmap.icon_arrow_down_black);
            viewFinder.textView(R.id.tab_kline_depth).setTextColor(getResources().getColor(R.color.blue));
            viewFinder.find(R.id.tab_indicator_kline).setVisibility(View.INVISIBLE);
            viewFinder.find(R.id.tab_indicator_depth).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        boolean isLandScape = (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
        if (isLandScape && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
            return false;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        //RateAndLocalManager.GetInstance(KlineExtActivity.this).SetCurLocalKind(KlineExtActivity.this, RateAndLocalManager.GetInstance(KlineExtActivity.this).getCurLocalKind());
        //横竖屏变化通知
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            boolean flag = tab_kline.selectIsLastIndex();
            if(flag){
                viewPagerKline.setCurrentItem(1);
            }
            showLandView();
            requestFullScreen(true);
            showTicker(currentTicker);
            switchTopMarketView(false);

        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            boolean flag = tab_kline.selectIsLastIndex();
            /*if(flag){
                viewPagerKline.setCurrentItem(0);
            }else{

            }*/
            synchronizedKindTab();
            showPortView();
            //topOptionView.setVisibility(View.GONE);
            requestFullScreen(false);
            showTicker(currentTicker);
            switchTopMarketView(true);

        }

    }

    private void switchDepthView() {
        switchKlineTabIndicator(false);
        switchShowKlineTabView(false);
        viewPagerKline.setCurrentItem(0);
    }

    /**
     * 切换头部行情view
     *
     * @param isVertical
     */
    private void switchTopMarketView(boolean isVertical) {
        if (isVertical) {

            if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())){
                //期权
                topOptionView.setVisibility(View.VISIBLE);
                topMarketView.setVisibility(View.GONE);
            }else{
                topOptionView.setVisibility(View.GONE);
                topMarketView.setVisibility(View.VISIBLE);
            }
        } else {
            topMarketView.setVisibility(View.GONE);
            topOptionView.setVisibility(View.GONE);
            updateCoinName();
        }

    }

    private void updateCoinName() {
        if (coinPairBean == null) {
            return;
        }

        if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
            ((TextView) findViewById(R.id.coinPairName)).setText(baseTokenName + "/" + quoteTokenName);
        }else if(KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())){
            //期权
            ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName());

        }else if(KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())){
            //合约
            ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName());
        }
    }


    public void initKlineFragmentTab() {
        itemsKline = new ArrayList<>();
        Bundle bundle = new Bundle();
        bundle.putString(AppData.INTENT.SYMBOLS, coinPair);
        bundle.putString(AppData.INTENT.EXCHANGE_ID, exchangeId);
        bundle.putString(AppData.INTENT.MERGE_DIGITS, mergeDigitsStr);
        bundle.putSerializable(AppData.INTENT.COINPAIR, coinPairBean);
        //深度
        DepthViewFragment depthViewFragment = new DepthViewFragment();
        depthViewFragment.setArguments(bundle);
        //K线
        //klineFragment = new KlineFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putString(AppData.INTENT.SYMBOLS, coinPair);
        bundle1.putString(AppData.INTENT.EXCHANGE_ID, exchangeId);
        bundle1.putString(AppData.INTENT.MERGE_DIGITS, mergeDigitsStr);
        bundle1.putSerializable(AppData.INTENT.COINPAIR, coinPairBean);
        klineFragment.setArguments(bundle1);
        itemsKline.add(new Pair<String, Fragment>(getString(R.string.string_depth), depthViewFragment));
        //itemsKline.add(new Pair<String, Fragment>(getString(R.string.string_times), minimLineFragment));
        itemsKline.add(new Pair<String, Fragment>(getString(R.string.string_kline), klineFragment));
        viewPagerKline.setAdapter(new KlineFragmentAdapter(getSupportFragmentManager(),itemsKline));
        tab.setTabTextColors(getResources().getColor(R.color.color_white),getResources().getColor(R.color.blue));
        viewPagerKline.setCurrentItem(1);
    }

    private void initOrderFragmentTab() {
        items = new ArrayList<>();
        bookListFragment = new BookListFragment(viewPager);
        DealPriceFragment dealPriceFragment = new DealPriceFragment(viewPager);
        Bundle bundle = new Bundle();
//        bundle.putString(AppData.INTENT.EXCHANGE_ID, exchangeId);
//        bundle.putString(AppData.INTENT.SYMBOLS, coinPair);
//        bundle.putString(AppData.INTENT.MERGE_DIGITS, mergeDigitsStr);
        bundle.putSerializable(AppData.INTENT.SYMBOLS, coinPairBean);
        bookListFragment.setArguments(bundle);
        dealPriceFragment.setArguments(bundle);
        items.add(new Pair<String, Fragment>(getString(R.string.string_entrust_order), bookListFragment));
        items.add(new Pair<String, Fragment>(getString(R.string.string_latest_deal), dealPriceFragment));
        if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
            //币币的K线有币种简介
            TokenBriefIntroductionFragment tokenBriefIntroductionFragment = new TokenBriefIntroductionFragment(viewPager);
            tokenBriefIntroductionFragment.setArguments(bundle);
            items.add(new Pair<String, Fragment>(getString(R.string.string_brief_introduction), tokenBriefIntroductionFragment));
        }
        if (KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())) {
            //合约简介
            ContractIntroductionFragment contractIntroductionFragment = new ContractIntroductionFragment(viewPager);
            contractIntroductionFragment.setArguments(bundle);
            items.add(new Pair<String, Fragment>(getString(R.string.string_brief_introduction), contractIntroductionFragment));
        }
        viewPager.setAdapter(new KlineFragmentAdapter(getSupportFragmentManager(),items));
        tab.setupWithViewPager(viewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white), getResources().getColor(R.color.color_black));
        tab.setTabMode(TabLayout.MODE_FIXED);
        tab.setTabGravity(TabLayout.GRAVITY_FILL);
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentOrderTabPosition = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        CommonUtil.setUpIndicatorWidthByReflex3(tab, 15, 15);
        /*viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                viewPager.resetHeight(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        viewPager.resetHeight(0);*/
    }

    @Override
    public void showTicker(TickerBean data) {
        if (data != null) {
            currentTicker = data;
            float riseFallAmount = KlineUtils.calRiseFallAmountFloat(data.getC(), data.getO());
            ((TextView) findViewById(R.id.latestPrice)).setText(NumberUtils.roundFormatDown(data.getC(), quoteDigit));
            ((TextView) findViewById(R.id.option_latestPrice)).setText(NumberUtils.roundFormatDown(data.getC(), quoteDigit));
            if (coinPairBean!=null && coinPairBean.getCoinType()== COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType() && coinPairBean.baseTokenFutures!=null) {
                //合约 使用displayTokenId
                String legalMoney = RateDataManager.CurRatePrice(coinPairBean.baseTokenFutures.getDisplayTokenId(), data.getC());
                legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
                ((TextView) findViewById(R.id.latestPrice2)).setText("≈" + legalMoney);
            }else{

                String legalMoney = RateDataManager.CurRatePrice(quoteToken, data.getC());
                legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
                ((TextView) findViewById(R.id.latestPrice2)).setText("≈" + legalMoney);
                ((TextView) findViewById(R.id.option_latestPrice2)).setText("≈" + legalMoney);
            }
            ((TextView) findViewById(R.id.highPrice)).setText(NumberUtils.roundFormatDown(data.getH(), quoteDigit));
            ((TextView) findViewById(R.id.option_highPrice)).setText(NumberUtils.roundFormatDown(data.getH(), quoteDigit));
            ((TextView) findViewById(R.id.lowPrice)).setText(NumberUtils.roundFormatDown(data.getL(), quoteDigit));
            ((TextView) findViewById(R.id.option_lowPrice)).setText(NumberUtils.roundFormatDown(data.getL(), quoteDigit));
//            ((TextView) findViewById(R.id.riseFallAmount)).setText(NumberUtils.roundFormatDown(riseFallAmount,2));
            if (isVerticalScreen) {
                ((TextView) findViewById(R.id.riseFallRatio)).setText(KlineUtils.calRiseFallRatio(data.getC(), data.getO()));
                KlineUtils.setMarketViewColor(riseFallAmount, findViewById(R.id.riseFallRatio));
//                ((TextView) findViewById(R.id.riseFallRatio)).setTextColor(SkinColorUtil.getWhite(this));
                ((TextView) findViewById(R.id.option_riseFallRatio)).setText(KlineUtils.calRiseFallRatio(data.getC(), data.getO()));
                KlineUtils.setMarketViewBgColor(riseFallAmount, findViewById(R.id.option_riseFallRatio));

                //KlineUtils.setMarketViewBgColor(riseFallAmount, findViewById(R.id.land_riseFallRatio));

//                ((TextView) findViewById(R.id.option_riseFallRatio)).setTextColor(SkinColorUtil.getWhite(this));
            } else {
                ((TextView) findViewById(R.id.riseFallRatio)).setText("(" + KlineUtils.calRiseFallRatio(data.getC(), data.getO()) + ")");
                findViewById(R.id.riseFallRatio).setBackgroundColor(getResources().getColor(R.color.transparent));
                KlineUtils.setMarketViewColor(riseFallAmount, findViewById(R.id.riseFallRatio));
            }

            ((TextView) findViewById(R.id.volume)).setText(io.bhex.baselib.utils.NumberUtils.handVolumeLength(data.getV(), coinPairBean.getCoinType()==COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType()?AppData.DIGIT_24H_AMOUNT_CONTACT : AppData.DIGIT_24H_AMOUNT));
            ((TextView) findViewById(R.id.option_volume)).setText(NumberUtils.roundFormatDown(data.getV(), AppData.DIGIT_24H_AMOUNT) + getString(R.string.string_option_unit));

            KlineUtils.setMarketViewColor(riseFallAmount, findViewById(R.id.latestPrice));
//            KlineUtils.setMarketViewColor(riseFallAmount, findViewById(R.id.latestPrice2));
            try {
                if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
                    //期权
                    double ratio = NumberUtils.div(data.getC(), coinPairBean.baseTokenOption.maxPayOff);
                    ((TextView) findViewById(R.id.option_lever)).setText(NumberUtils.roundFormatDown(ratio, 2) + "X");
                }
            } catch (Exception e) {

            }

        }
    }

    @Override
    public void getTickerFailed(String msg) {

    }

    @Override
    public void setCurrentPriceDigits(PriceDigits response) {
        if (response == null) {
            return;
        }

        digitsList = response.getArray();
        if (!digitsList.isEmpty()) {
            String digits = digitsList.get(0).getDigits();
            EventBus.getDefault().post(new PriceDigitsEvent(digits));
        }

    }

    @Override
    public String getExchangeId() {
        return exchangeId;
    }

    @Override
    public String getSymbols() {
        return coinPair;
    }


    /**
     * 请求是否全屏显示
     *
     * @param isFullScrren
     */
    private void requestFullScreen(boolean isFullScrren) {
        if (isFullScrren) {
            // 隐藏标题栏
            //requestWindowFeature(Window.FEATURE_NO_TITLE);//适用于活动继承Activity
            // 隐藏状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

    }

    @Override
    public void OnIndexChanged() {
        if (coinPairBean != null && coinPairBean.baseTokenOption != null) {

            String indexData = NumberUtils.roundFormatDown(AssetUtilsManager.GetInstance().getSymbolIndexOfOption(coinPairBean.baseTokenOption.indexToken), quoteDigit);
            viewFinder.textView(R.id.option_exercise_point).setText(indexData);
        }
    }

    private void getSettleStatus() {
        if (coinPairBean == null) {
            return;
        }
        OptionApi.RequestOptionStatus(coinPairBean.getSymbolId(), new SimpleResponseListener<OptionSymbolStatusBean>() {
            @Override
            public void onSuccess(OptionSymbolStatusBean response) {
                super.onSuccess(response);
                if (!CodeUtils.isSuccess(response, false)) {
                    return;
                }

                List<OptionSymbolStatusBean.OptionSymbolStatus> data = response.array;

                if (data == null) {
                    return;
                }

                for (OptionSymbolStatusBean.OptionSymbolStatus bean : data) {
                    if (bean != null && !TextUtils.isEmpty(coinPairBean.getSymbolId())
                            && coinPairBean.getSymbolId().equalsIgnoreCase(bean.symbolId)) {
                        mOptionSymbolStatus = bean;
                    }
                }
            }
        });
    }

}
